package com.yiren.manager.ctrl.department;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.StringUtil;
import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.Favorites;
import com.yiren.core.utils.FileUtil;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.PropertyConfigurer;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrAccount;
import com.yiren.entity.YrAccountModelConfig;
import com.yiren.entity.YrDepartment;
import com.yiren.entity.YrMealCard;
import com.yiren.entity.YrStaffInfo;
import com.yiren.entity.YrSubjectRoom;
import com.yiren.entity.YrUserRfidCard;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.base.YrUserRfidCardForm;
import com.yiren.manager.form.department.YrDepartmentForm;
import com.yiren.manager.form.department.YrStaffInfoForm;
import com.yiren.manager.form.department.YrSubjectRoomForm;
import com.yiren.manager.form.personnel.YrAccountForm;
import com.yiren.manager.form.system.YrAccountModelConfigForm;
import com.yiren.manager.form.system.YrSysModelForm;
import com.yiren.manager.service.iface.base.YrUserRfidCardService;
import com.yiren.manager.service.iface.department.YrDepartmentService;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.department.YrSubjectRoomService;
import com.yiren.manager.service.iface.personnel.YrAccountService;
import com.yiren.manager.service.iface.system.YrAccountModelConfigService;
import com.yiren.manager.service.iface.system.YrSysModelService;
import com.yiren.manager.utils.ObjectUtils;

/**
 * 职工管理控制类
 * @author yanwenhao
 *
 */
@RequestMapping("staffInfo")
@Controller
public class YrStaffInfoController extends GenericController<YrStaffInfoForm, YrStaffInfo>{

	@Autowired
	private YrStaffInfoService selfService;
	
	@Autowired
	private YrDepartmentService departmentService;
	
	@Autowired
	private YrAccountService accountService;
	
	@Autowired
	private YrSubjectRoomService subjectRoomService;
	
	@Autowired
	private YrAccountModelConfigService accountModelConfigService;
	
	@Autowired
	private YrSysModelService sysModelService;
	
	@Autowired
	private YrUserRfidCardService userRfidCardService;
	
	//保存实体  
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrStaffInfoForm> save(String data) throws SwallowException, MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		HTTPResult<YrStaffInfoForm> result = new HTTPResult<YrStaffInfoForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrStaffInfoForm form = tool.mapper("staffInfo", YrStaffInfoForm.class);
		if(null==form){
			throwExp("param.error");
		}
		
		String sqlWhere ;
		if(form.getManagerOfSubjectRoom()==1){//是科室负责人
			String subjectRoomId = form.getSubjectRoomId();
			sqlWhere = "subject_room_id=?1 AND status=0 AND manager_of_subject_room=1";
			QueryResult<YrStaffInfo> qrStaffInfo = selfService.find(YrStaffInfo.class, sqlWhere, new Object[]{subjectRoomId});
			if(qrStaffInfo.getTotalRecord()>0){
				throwExp("该科室已有负责人，请勿重复添加");
			}
		} 
		YrMealCard mealCard = null;
		if(null==form.getStaffId()||form.getStaffId().isEmpty()){
			sqlWhere = "name=?1 AND card_id=?2";
			QueryResult<YrStaffInfo> qrStaffInfo = selfService.find(YrStaffInfo.class, sqlWhere, new Object[]{form.getName(),form.getCardId()});
			if(qrStaffInfo.getTotalRecord()>0){
				throwExp("该员工已存在，请勿重复添加");
			}
			
			form.setStaffId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
			mealCard  = new YrMealCard();
			mealCard.setMealCardId(UUIDGenerator.getUUID());
			mealCard.setCardPersonId(form.getStaffId());
			mealCard.setCardPersonName(form.getName());
			mealCard.setCardCardId(form.getCardId());
			mealCard.setBalance(Float.valueOf(0));
			mealCard.setCardType(0);
			mealCard.setCreateTime(new Date());
			mealCard.setCreateId(form.getCreateId());
			mealCard.setPersonType(2);
		}
		form.setUpdateTime(new Date());
		if(null!=form.getImgBase64()&&!form.getImgBase64().isEmpty()){
			YrStaffInfo entity = selfService.findOne(form.getStaffId());
			if(entity!=null){
				FileUtil.deleteFile(String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url"))+entity.getPhotoUrl());
			}
			form.setPhotoUrl(FileUtil.saveBase64(form.getImgBase64(),String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url"))));
		}
		
		YrStaffInfo entity = ObjectUtils.objectToObject(form, YrStaffInfo.class);
		Favorites favorites = new Favorites();
		favorites.putFavorite(YrStaffInfo.class, entity);
		favorites.putFavorite(YrMealCard.class, mealCard);
		
		
		selfService.addByFavorites(favorites);
		
		return result;
	}
	
	/**获取一条记录*/
	@RequestMapping("findOne")
	@ResponseBody
	public HTTPResult<YrStaffInfoForm> findOne(String id) throws MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		HTTPResult<YrStaffInfoForm> result = new HTTPResult<YrStaffInfoForm>();
		if(null==id){
			throwExp("param.error");
		}
		YrStaffInfo entity = selfService.findOne(id);
		List<YrStaffInfoForm> formList = new ArrayList<YrStaffInfoForm>();
		YrStaffInfoForm staffInfoForm = ObjectUtils.objectToObject(entity, YrStaffInfoForm.class);
		
		YrDepartment department = departmentService.findOne(staffInfoForm.getDepartmentId()==null?"":staffInfoForm.getDepartmentId());
		if(null!=department){
			staffInfoForm.setDepartmentForm(ObjectUtils.objectToObject(department,YrDepartmentForm.class));
		}
		YrSubjectRoom subjectRoom = subjectRoomService.findOne(staffInfoForm.getSubjectRoomId()==null?"":staffInfoForm.getSubjectRoomId());
		if(null!=subjectRoom){
			staffInfoForm.setSubjectRoomForm(ObjectUtils.objectToObject(subjectRoom, YrSubjectRoomForm.class));
		}
		String sqlWhere = "staff_id=?1";
		QueryResult<YrAccount> qrAccount = accountService.find(YrAccount.class, sqlWhere, new Object[]{entity.getStaffId()});
		if(qrAccount.getTotalRecord()>0){
			YrAccount account = qrAccount.getResultList().get(0);
			staffInfoForm.setAccountForm(ObjectUtils.objectToObject(account, YrAccountForm.class));
		}
		//设置头像路径
//		if(!StringUtil.isEmpty(staffInfoForm.getPhotoUrl())){
//			staffInfoForm.setPhotoUrl(String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url")+staffInfoForm.getPhotoUrl()));
//		}
		formList.add(staffInfoForm);
		result.setData(formList);
		return result;
	}
	
	/**
	 * 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrStaffInfoForm> find(String searchVal) throws Exception{
		HTTPResult<YrStaffInfoForm> result = new HTTPResult<YrStaffInfoForm>();
		if(null==searchVal){
			throwExp("param.error");
		}
		String sqlWhere = "name=?1 OR card_id=?2";
		QueryResult<YrStaffInfo> qr = selfService.find(YrStaffInfo.class, sqlWhere, new Object[]{searchVal,searchVal});
		
		List<YrStaffInfoForm> formList = new ArrayList<YrStaffInfoForm>();
		for(YrStaffInfo entity : qr.getResultList()){
			YrStaffInfoForm form = toForm(entity);
			YrDepartment department = departmentService.findOne(form.getDepartmentId()==null?"":form.getDepartmentId());
			if(null!=department){
				form.setDepartmentForm(ObjectUtils.objectToObject(department,YrDepartmentForm.class));
			}
			YrSubjectRoom subjectRoom = subjectRoomService.findOne(form.getSubjectRoomId()==null?"":form.getSubjectRoomId());
			if(null!=subjectRoom){
				form.setSubjectRoomForm(ObjectUtils.objectToObject(subjectRoom, YrSubjectRoomForm.class));
			}
			sqlWhere = "staff_id=?1";
			QueryResult<YrAccount> qrAccount = accountService.find(YrAccount.class, sqlWhere, new Object[]{entity.getStaffId()});
			if(qrAccount.getTotalRecord()>0){
				YrAccount account = qrAccount.getResultList().get(0);
				form.setAccountForm(ObjectUtils.objectToObject(account, YrAccountForm.class));
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	@RequestMapping("findByDepartment")
	@ResponseBody
	public HTTPResult<YrStaffInfoForm> findByDepartment(String departmentId) throws Exception{
		HTTPResult<YrStaffInfoForm> result = new HTTPResult<YrStaffInfoForm>();
		if(null==departmentId){
			throwExp("参数有误");
		}
		String sqlWhere = "department_id=?1";
		List<YrStaffInfoForm> formList = new ArrayList<YrStaffInfoForm>();
		QueryResult<YrStaffInfo> qr = selfService.find(YrStaffInfo.class,sqlWhere, new Object[]{departmentId});
		for(YrStaffInfo entity : qr.getResultList()){
			YrStaffInfoForm form = toForm(entity);
			YrDepartment department = departmentService.findOne(form.getDepartmentId()==null?"":form.getDepartmentId());
			if(null!=department){
				form.setDepartmentForm(ObjectUtils.objectToObject(department,YrDepartmentForm.class));
			}
			YrSubjectRoom subjectRoom = subjectRoomService.findOne(form.getSubjectRoomId()==null?"":form.getSubjectRoomId());
			if(null!=subjectRoom){
				form.setSubjectRoomForm(ObjectUtils.objectToObject(subjectRoom, YrSubjectRoomForm.class));
			}
			sqlWhere = "staff_id=?1";
			QueryResult<YrAccount> qrAccount = accountService.find(YrAccount.class, sqlWhere, new Object[]{entity.getStaffId()});
			if(qrAccount.getTotalRecord()>0){
				YrAccount account = qrAccount.getResultList().get(0);
				form.setAccountForm(ObjectUtils.objectToObject(account, YrAccountForm.class));
				sqlWhere = "account_id=?1";
				QueryResult<YrAccountModelConfig> qrAccountModelConfig = accountModelConfigService.find(YrAccountModelConfig.class, sqlWhere,new Object[]{form.getAccountForm().getId()});
				List<YrAccountModelConfigForm> accountModelConfigForms = new ArrayList<YrAccountModelConfigForm>();
				for(YrAccountModelConfig accountModelConfig : qrAccountModelConfig.getResultList()){
					YrAccountModelConfigForm accountModelConfigForm = ObjectUtils.objectToObject(accountModelConfig, YrAccountModelConfigForm.class);
					YrSysModelForm sysModelForm =ObjectUtils.objectToObject(sysModelService.findOne(accountModelConfigForm.getSysModelId()), YrSysModelForm.class) ;
					accountModelConfigForm.setSysModelForm(sysModelForm);
					accountModelConfigForms.add(accountModelConfigForm);
				}
				form.setAccountModelConfigForms(accountModelConfigForms);
			}
			formList.add(form);
		}
		
		result.setData(formList);
		return result;
	};
	
	@RequestMapping("deleteOne")
	@ResponseBody
	public HTTPResult<YrStaffInfoForm> deleteOne(String id) throws MyException{
		HTTPResult<YrStaffInfoForm> result = new HTTPResult<YrStaffInfoForm>();
		
		if(null==id){
			throwExp("参数有误");
		}
		YrStaffInfo entity = selfService.findOne(id);
		if(null==entity){
			throwExp("删除失败，找不到对应职工");
		}
		if(!StringUtil.isEmpty(entity.getPhotoUrl())){
			FileUtil.deleteFile(String.valueOf(PropertyConfigurer.getContextProperty("yiren.img.save.url"))+entity.getPhotoUrl());
		}
		selfService.delete(id);
		return result;
	}
	
	/**
	 * 根据有无rfid卡查找员工
	 * @param has
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("findStaffByRfid")
	@ResponseBody
	public HTTPResult<YrStaffInfoForm> findStaffByRfid(Integer has) throws Exception{
		HTTPResult<YrStaffInfoForm> result = new HTTPResult<YrStaffInfoForm>();
		String hasSql = "";
		if(has==1){//有卡
			hasSql=">0";
		}else{//没卡
			hasSql="=0";
		}
		hasSql += "ORDER BY a.subjectRoomName DESC , a.departmentName DESC";
		String sql = "SELECT a FROM YrStaffInfo a "+
				" WHERE (SELECT count(b) from YrUserRfidCard b WHERE b.userRelationId=a.staffId)"+hasSql;
		
		List<YrStaffInfo> staffInfoList = selfService.findByJPQL(sql,new Object[]{});
		
		List<YrStaffInfoForm> staffInfoForms = new ArrayList<YrStaffInfoForm>();
		String sqlRfid = "user_relation_id=?1";
		for(YrStaffInfo staffInfo : staffInfoList){
			YrStaffInfoForm staffInfoForm = toForm(staffInfo);
			if(has==1){
				QueryResult<YrUserRfidCard> qrUserRfid = userRfidCardService.find(YrUserRfidCard.class,sqlRfid, new Object[]{staffInfo.getStaffId()});
				ArrayList<YrUserRfidCardForm> userRfidCardForms = new ArrayList<YrUserRfidCardForm>();
				for(YrUserRfidCard userRfidCard : qrUserRfid.getResultList()){
					YrUserRfidCardForm userRfidCardForm = ObjectUtils.objectToObject(userRfidCard, YrUserRfidCardForm.class);
					userRfidCardForms.add(userRfidCardForm);
				}
				staffInfoForm.setUserRfidCardForms(userRfidCardForms);
			}
			staffInfoForms.add(staffInfoForm);
		}
		result.setData(staffInfoForms);
		return result;
	}
	
	@Override
	public YrStaffInfoForm toForm(YrStaffInfo e) throws Exception {
		YrStaffInfoForm form = ObjectUtils.objectToObject(e, YrStaffInfoForm.class);
		return form;
	}

	@Override
	public YrStaffInfo toEntity(YrStaffInfoForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
